import orchestrationService from '@/api/services/orchestrationService';
import { GetWorkBenhList } from '@/common';
import { AppStatusEnum, AppWorkbenchType } from '@/common/app/constants';
import NotData from '@/components/NotData';
import AvatarDisplay from '@/components/work-modal/components/AvatarDisplay';
import { useUserInfo } from '@/store/userStore';
import { formatDataNoTime } from '@/utils/time';
import { useRef } from 'react';
import { useNavigate } from 'react-router-dom';

interface MobilProps {
  name: string;
  appList: GetWorkBenhList[];
  isLoading?: boolean;
  onScroll?: () => void;
  flag?: boolean;
  setflag?: (data: boolean) => void;
  height?: number;
  isGetFusion?: boolean;
  onGetFusionCollect?: (data: GetWorkBenhList) => void;
}

export default function MobileContent({
  name,
  isLoading,
  appList,
  flag,
  isGetFusion = false,
  onScroll,
  setflag = () => {},
  height,
  onGetFusionCollect = () => {},
}: MobilProps) {
  const workAllRef = useRef<HTMLDivElement>(null);
  const { role } = useUserInfo();
  const router = useNavigate();
  const type =
    name === '1' ? 'manager' : name === '2' ? 'market' : name === '3' ? 'public' : 'fusion';

  //下拉触底操作
  const Scroll = () => {
    if (workAllRef.current) {
      let height1 = workAllRef.current.clientHeight; // 可以得到我们设置的高度 (不包括滚动的高度)
      let height2 = workAllRef.current.scrollTop; // 当滚动时被卷去的高度
      let height3 = workAllRef.current.scrollHeight; // 全部的高度 包括滚动的高度
      if (height1 + height2 + 20 > height3 && !flag) {
        // 当距离底部20 则会触发
        // 加了flag 是为了防止反复触发
        setflag(true);
        // console.log('触发了');
        //这里进行请求
        onScroll && onScroll();
        //成功后关闭
        // setTimeout(() => {
        //   setflag(false)
        // }, 1000)
      }
    }
  };
  async function goToApplication(e: React.MouseEvent, obj: GetWorkBenhList) {
    e.stopPropagation();
    e.preventDefault();

    if (isGetFusion) {
      onGetFusionCollect(obj);
      return;
    }

    // 公共函数：打开聊天应用
    const openChatApp = (appId: string, shareId: string, type: string) => {
      router(
        type == 'fusion'
          ? `/fusion?appId=${appId}&shareId=${shareId}&isPublic=true`
          : `/apps/chat?appId=${appId}&shareId=${shareId}&isPublic=true`,
      );
    };

    if (type === 'manager') {
      // 待审批中的应用，审核员跳转审核页面
      if (obj.review_status === AppStatusEnum.pending && role?.code === 'super_admin') {
        router(`/apps/viewOrchestration?appType=${obj.app_type}&appId=${obj.app_id}`);
        return;
      }
      // 统一处理管理员路由
      const getShareId = async () => {
        return (
          obj.share_id ||
          (await orchestrationService.getAppDetailV2(obj.app_id, AppWorkbenchType.manage)).share_id
        );
      };

      const shareId = await getShareId();
      obj.app_type === 'workflow'
        ? router(`/app/workflow?appId=${obj.app_id}&shareId=${shareId}`)
        : router(`/apps/orchestration?appId=${obj.app_id}&shareId=${shareId}`);
      return;
    }

    if (type === 'public' || type === 'fusion') {
      // 优先使用现有 share_id
      if (obj.share_id) {
        openChatApp(obj.app_id, obj.share_id, obj.app_type);
        return;
      }

      // 不存在时才请求
      const res = await orchestrationService.getAppDetailV2(obj.app_id, AppWorkbenchType.public);
      console.log('res', res);

      if (res.app_id && res.share_id) {
        openChatApp(res.app_id, res.share_id, obj.app_type);
      }
    }
  }

  return (
    <div>
      {appList.length === 0 && isLoading ? (
        <div className="flex h-[570px] items-center">
          <NotData iconSize={80} textClassName={'text-sm'} />
        </div>
      ) : (
        <div
          ref={workAllRef}
          onScroll={Scroll}
          className="workbench-all"
          style={{
            overflowY: 'auto',
            maxHeight:
              ((role?.code === 'super_admin' || role?.code === 'admin') && name === '1') ||
              name === '2'
                ? // ? `83vh`
                  // : `88vh`,
                  `calc(83vh - ${height}px)`
                : `calc(86vh - ${height}px)`,
          }}
        >
          {/* 可管理应用 */}
          {(appList.length > 0 || role?.code === 'super_admin' || role?.code === 'admin') && (
            <div>
              {appList.map((item: any, index: number) => {
                return (
                  <div
                    key={index}
                    className="mb-3 h-[138px] rounded-default bg-[#FDFEFE] p-3"
                    onClick={(e) => goToApplication(e, item)}
                  >
                    <div className="flex items-center ">
                      <AvatarDisplay src={item.app_logo} size={40} className="h-[48px] w-[48px]" />
                      <div className="ml-2 w-full">
                        <div className="   text-text-5 ">
                          <div className="h-7 min-w-[50px]  truncate text-base font-bold leading-6">
                            {item.app_name}
                          </div>
                        </div>
                        <div className=" flex  items-center justify-between">
                          <div
                            className=" h-[18px] min-w-[50px] rounded-small px-[6px]  text-center text-xs leading-[16px]"
                            style={
                              item.app_type == 'agent'
                                ? { background: '#C0F8EF', color: '#00454D' }
                                : item.app_type == 'workflow'
                                ? { background: '#E3C7FD', color: '#280976' }
                                : { background: '#BADEFF', color: '#002379' }
                            }
                          >
                            {item.app_type == 'agent'
                              ? '智能体'
                              : item.app_type == 'workflow'
                              ? '工作流'
                              : '融合应用'}
                          </div>
                          <div className="flex h-5 items-center text-xs">
                            <span className="  whitespace-nowrap text-text-2">By</span>
                            <div className="ml-2 flex max-w-[10em] items-center text-text-3">
                              <div className="max-w-[6em] truncate">{item.group_name}</div>
                              <div className=" whitespace-nowrap">/</div>
                              <div className="max-w-[6em] truncate"> {item.user_name}</div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="mt-3 h-5 truncate  text-sm text-[#4E5969]">
                      <div className="text text-xs">
                        {item.review_status === 'reject' && '驳回原因:'}
                      </div>
                      {item.review_status === 'reject'
                        ? item.review_description
                        : item.app_description}
                    </div>

                    <div className=" flex h-10 items-center justify-between rounded-md  ">
                      <div className=" text-xs text-text-3">
                        {formatDataNoTime(item.create_time)}
                        <span className="ml-1">更新</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
